﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Elderos.Highlight.Rules;
using Elderos.Highlight.Search;
using Elderos.Ontology;

namespace Elderos.Highlight
{
    public abstract class RankingRule
    {
        protected IOntologyData Ontology { get; private set; }

        protected RankingRule(IOntologyData ontology)
        {
            Ontology = ontology;

            InitializeFields();
        }

        private void InitializeFields()
        {
            Type type = this.GetType();
            var attribute = (RankingRuleAttribute) type.GetCustomAttributes(typeof(RankingRuleAttribute), true).First();
            Name = attribute.Name;
            Flags = attribute.Flags;
        }

        public RuleType Flags { get; set; }

        public string Name { get; private set; }

        protected abstract Task<Dictionary<TextEntity, IRuleResult>> InnerRank(HighlightResult highlightResult);

#pragma warning disable 1998
        public async virtual Task Initialize(List<Func<HighlightResult, Task>> funcs)
#pragma warning restore 1998
        {}

        public async Task Rank(HighlightResult highlightResult)
        {
            var ruleResults = await InnerRank(highlightResult);
            foreach (var entity in highlightResult.Positions.SelectMany(x => x.EntitiesFlattened))
            {
                IRuleResult ruleResult;
                if (!ruleResults.TryGetValue(entity, out ruleResult))
                    ruleResult = EmptyResult;
                entity.FactorValues.AddRange(ruleResult.GetFactorValues());
            }
        }

        public abstract IRuleResult EmptyResult { get; }
    }
}
